<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 新增家庭搜索 -->
      <el-form-item label="家庭" prop="familyId" style="width: 200px;">
        <el-select
            v-model="queryParams.familyId"
            placeholder="选择家庭"
            clearable
            @change="handleFamilyFilter"
        >
          <el-option
              v-for="family in familyOptions"
              :key="family.familyId"
              :label="family.familyName"
              :value="family.familyId"
          />
        </el-select>
      </el-form-item>

      <!-- 新增房间搜索 -->
      <el-form-item label="房间" prop="roomId" style="width: 200px;">
        <el-select
            v-model="queryParams.roomId"
            placeholder="先选择家庭"
            clearable
            :disabled="!queryParams.familyId"
            @change="handleRoomFilter"
        >
          <el-option
              v-for="room in filteredSearchRooms"
              :key="room.roomId"
              :label="room.roomName"
              :value="room.roomId"
          />
        </el-select>
      </el-form-item>

<!--      &lt;!&ndash; 修改设备ID搜索 &ndash;&gt;-->
<!--      <el-form-item label="设备ID" prop="deviceId" style="width: 250px;">-->
<!--        <el-select-->
<!--            v-model="queryParams.deviceId"-->
<!--            placeholder="先选择房间"-->
<!--            clearable-->
<!--            :disabled="!queryParams.roomId"-->
<!--        >-->
<!--          <el-option-->
<!--              v-for="device in filteredSearchDevices"-->
<!--              :key="device.deviceId"-->
<!--              :label="`${device.deviceId} (甲醛传感器)`"-->
<!--              :value="device.deviceId"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="甲醛浓度" prop="formaldehydeLevel">
        <el-input
            v-model="queryParams.formaldehydeLevel"
            placeholder="请输入甲醛浓度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker clearable
                        v-model="queryParams.recordTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择记录时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['airsystem:formaldehyde:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['airsystem:formaldehyde:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['airsystem:formaldehyde:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formaldehydeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="记录ID" align="center" prop="recordId" />-->
      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>
      <el-table-column label="家庭名称" align="center">
        <template #default="scope">
          {{ scope.row._familyName }}
        </template>
      </el-table-column>

      <el-table-column label="房间名称" align="center">
        <template #default="scope">
          {{ scope.row._roomName }}
        </template>
      </el-table-column>


<!--      <el-table-column label="设备ID" align="center" prop="deviceId" >-->
<!--      <template #default="scope">-->
<!--        设备ID:{{ scope.row.deviceId }} 甲醛传感器-->
<!--      </template>-->
<!--      </el-table-column>-->
      <el-table-column label="甲醛浓度" align="center" prop="formaldehydeLevel" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['airsystem:formaldehyde:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['airsystem:formaldehyde:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改甲醛浓度记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formaldehydeRef" :model="form" :rules="rules" label-width="80px">

        <!-- 新增家庭选择 -->
        <el-form-item label="家庭名称" prop="familyId">
          <el-select
              v-model="form.familyId"
              placeholder="请选择家庭"
              clearable
              @change="handleFamilyChange"
          >
            <el-option
                v-for="family in familyOptions"
                :key="family.familyId"
                :label="family.familyName"
                :value="family.familyId"
            />
          </el-select>
        </el-form-item>

        <!-- 新增房间选择 -->
        <el-form-item label="房间名称" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请先选择家庭"
              clearable
              :disabled="!form.familyId"
              @change="handleRoomChange"
          >
            <el-option
                v-for="room in filteredRooms"
                :key="room.roomId"
                :label="room.roomName"
                :value="room.roomId"
            />
          </el-select>
        </el-form-item>

        <!-- 修改设备选择 -->
        <el-form-item label="设备类型" prop="deviceId">
          <el-select
              v-model="form.deviceId"
              placeholder="请先选择房间"
              clearable
              :disabled="!form.roomId"
          >
<!--            :label="`${device.deviceId} (${getDeviceType(device.deviceName)})`"-->
            <el-option
                v-for="device in filteredDevices"
                :key="device.deviceId"
                :label="`${getDeviceType(device.deviceName)}`"
                :value="device.deviceId"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="甲醛浓度" prop="formaldehydeLevel">
          <el-input v-model="form.formaldehydeLevel" placeholder="请输入甲醛浓度" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Formaldehyde">
import { listFormaldehyde, getFormaldehyde, delFormaldehyde, addFormaldehyde, updateFormaldehyde } from "@/api/airsystem/formaldehyde";
import { listDevices } from "@/api/airsystem/devices";
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
// 在顶部添加接口引用
import { listRooms } from "@/api/airsystem/rooms";
import { listFamilies } from "@/api/airsystem/families";
const { proxy } = getCurrentInstance();

const formaldehydeList = ref([]);
const deviceOptions = ref([]);
const filteredDeviceOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceId: null,
    formaldehydeLevel: null,
    recordTime: null
  },
  rules: {
    familyId: [
      { required: true, message: "必须选择家庭", trigger: "change" }
    ],
    roomId: [
      { required: true, message: "必须选择房间", trigger: "change" }
    ],
    deviceId: [
      { required: true, message: "必须选择设备", trigger: "change" }
    ],
    formaldehydeLevel: [
      { required: true, message: "甲醛浓度不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


// 在setup区域添加响应式数据
const roomOptions = ref([]);
const familyOptions = ref([]);
// 分页获取所有房间
async function getAllRooms() {
  let allRooms = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listRooms({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allRooms = [...allRooms, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allRooms;
  } catch (error) {
    console.error("获取房间失败:", error);
    return [];
  }
}
// 分页获取所有家庭
async function getAllFamilies() {
  let allFamilies = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listFamilies({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allFamilies = [...allFamilies, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allFamilies;
  } catch (error) {
    console.error("获取家庭失败:", error);
    return [];
  }
}


/** 可靠获取所有设备的方法 */
async function getAllDevices() {
  let allDevices = [];
  let pageNum = 1;
  const pageSize = 100; // 每页大小

  try {
    while (true) {
      const response = await listDevices({
        pageNum,
        pageSize
      });

      // 检查返回数据是否有效
      if (!response.rows || response.rows.length === 0) {
        break;
      }

      // 合并数据
      allDevices = [...allDevices, ...response.rows];

      // 判断是否还有更多数据
      if (response.rows.length < pageSize) {
        break;
      }

      pageNum++;
    }
    return allDevices;
  } catch (error) {
    console.error("分页获取设备失败:", error);
    proxy.$modal.msgError("获取设备数据失败");
    return [];
  }
}

/** 查询设备列表并过滤出deviceName="4"的设备 */
async function getDeviceList() {
  loading.value = true;
  try {
    // 获取所有设备
    const allDevices = await getAllDevices();

    // 存储所有设备
    deviceOptions.value = allDevices;

    // 严格筛选甲醛传感器（deviceName="4"）
    filteredDeviceOptions.value = allDevices.filter(
        device => device.deviceName === "4"
    );

    console.log('获取到的设备总数:', allDevices.length);
    console.log('甲醛传感器数量:', filteredDeviceOptions.value.length);

    // 如果没有找到甲醛传感器，显示提示
    if (filteredDeviceOptions.value.length === 0) {
      proxy.$modal.msgWarning("系统中未找到甲醛传感器设备");
    }

  } catch (error) {
    console.error("处理设备数据失败:", error);
    proxy.$modal.msgError("获取设备列表失败");
  } finally {
    loading.value = false;
  }
}

/** 查询甲醛浓度记录列表 */
async function getList() {
  try {
    loading.value = true;
    const response = await listFormaldehyde(queryParams.value);
    formaldehydeList.value = response.rows.filter(record => {
      // 获取设备信息
      const device = deviceOptions.value.find(d => d.deviceId === record.deviceId);
      if (!device) return false;

      // 家庭过滤
      const familyMatch = queryParams.value.familyId
          ? roomOptions.value.find(r => r.roomId === device.roomId)?.familyId === queryParams.value.familyId
          : true;

      // 房间过滤
      const roomMatch = queryParams.value.roomId
          ? device.roomId === queryParams.value.roomId
          : true;

      // 设备过滤
      const deviceMatch = queryParams.value.deviceId
          ? device.deviceId === queryParams.value.deviceId
          : true;

      return familyMatch && roomMatch && deviceMatch;
    }).map(record => {
      // 找到设备
      const device = deviceOptions.value.find(d => d.deviceId === record.deviceId);
      // 找到房间
      const room = roomOptions.value.find(r => r.roomId === device?.roomId);
      // 找到家庭
      const family = familyOptions.value.find(f => f.familyId === room?.familyId);
      return {
        ...record,
        _familyName: family?.familyName || '未知家庭',
        _roomName: room?.roomName || '未知房间'
      };
    });
    total.value = response.total;
  } catch (error) {
    console.error("获取记录失败:", error);
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    deviceId: null,
    formaldehydeLevel: null,
    recordTime: null
  };
  proxy.resetForm("formaldehydeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceId: null,
    formaldehydeLevel: null,
    recordTime: null
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加甲醛浓度记录";
}

/** 修改按钮操作 */
/** 修改按钮操作 */
async function handleUpdate(row) {
  try {
    reset();
    const _recordId = row.recordId || ids.value;
    const response = await getFormaldehyde(_recordId);

    // 找到关联设备
    const device = deviceOptions.value.find(d => d.deviceId === response.data.deviceId);
    // 找到房间
    const room = roomOptions.value.find(r => r.roomId === device?.roomId);

    form.value = {
      ...response.data,
      familyId: room?.familyId,
      roomId: device?.roomId
    };

    open.value = true;
    title.value = "修改甲醛浓度记录";
  } catch (error) {
    console.error("获取记录详情失败:", error);
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await proxy.$refs["formaldehydeRef"].validate();
    if (valid) {
      if (form.value.recordId != null) {
        await updateFormaldehyde(form.value);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await addFormaldehyde(form.value);
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    }
  } catch (error) {
    console.error("提交表单失败:", error);
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const _recordIds = row.recordId || ids.value;
    await proxy.$modal.confirm(`是否确认删除记录编号为"${_recordIds}"的数据？`);
    await delFormaldehyde(_recordIds);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (error) {
    console.error("删除记录失败:", error);
  }
}


// 家庭选择事件
const handleFamilyFilter = () => {
  queryParams.value.roomId = null;
  queryParams.value.deviceId = null;
  handleQuery();
};

// 房间选择事件
const handleRoomFilter = () => {
  queryParams.value.deviceId = null;
  handleQuery();
};


// 新增计算属性
const filteredRooms = computed(() => {
  return roomOptions.value.filter(room =>
      room.familyId === form.value.familyId
  );
});

const filteredDevices = computed(() => {
  return deviceOptions.value
      .filter(device =>
          device.roomId === form.value.roomId &&
          device.deviceName === "4" // 保持甲醛传感器过滤
      );
});

// 设备类型转换方法
const getDeviceType = (deviceName) => {
  const deviceTypeMap = {
    '4': '甲醛传感器',
    // 其他设备类型映射...
  };
  return deviceTypeMap[deviceName] || '未知设备';
};

// 事件处理
const handleFamilyChange = () => {
  form.value.roomId = null;
  form.value.deviceId = null;
};

const handleRoomChange = () => {
  form.value.deviceId = null;
};


// 搜索用房间过滤
const filteredSearchRooms = computed(() => {
  return roomOptions.value.filter(room =>
      room.familyId === queryParams.value.familyId
  );
});

// 搜索用设备过滤
const filteredSearchDevices = computed(() => {
  if (!queryParams.value.roomId) return [];
  return deviceOptions.value.filter(device =>
      device.roomId === queryParams.value.roomId &&
      device.deviceName === "4"
  );
});




// 修改onMounted
onMounted(async () => {
  await Promise.all([
    getDeviceList(),
    getAllRooms().then(rooms => roomOptions.value = rooms),
    getAllFamilies().then(families => familyOptions.value = families)
  ]);
  getList();
});
</script>
